﻿using System;
using System.Web.UI;

namespace N2.ComponentModel
{
	public class CurrentItemPropertyHolder<ItemType>
		where ItemType :ContentItem
	{
		public event EventHandler Changed;

		protected virtual void OnChanged()
		{
			if (null != this.Changed) {
				this.Changed(this, EventArgs.Empty);
			}
		}

		protected virtual int? СurrentItemId { get; set; }

		ItemType m_currentItem;

		public ItemType CurrentItem {
			get {
				return this.m_currentItem
					?? (this.m_currentItem =
						this.СurrentItemId.HasValue
							? (ItemType)Context.Persister.Get(this.СurrentItemId.Value)
							: default(ItemType));
			}
			set {
				this.m_currentItem = value;

				if (null != value) {
					var _oldId = this.СurrentItemId;
					this.СurrentItemId = value.ID;

					if (_oldId != value.ID) {
						this.СurrentItemId = value.ID;
						this.OnChanged();
					}
				} else {
					this.СurrentItemId = default(int?);
				}
			}
		}
	}

	public class CurrentItemPropertyHolder : CurrentItemPropertyHolder<ContentItem> { }

	public class ViewStateCurrentItemPropertyHolder<ItemType> : CurrentItemPropertyHolder<ItemType>
		where ItemType: ContentItem
	{
		readonly StateBag m_vs;

		public ViewStateCurrentItemPropertyHolder(StateBag viewState)
		{
			this.m_vs = viewState;
		}

		protected override int? СurrentItemId
		{
			get { return this.m_vs["CurrentItemId"] as int?; }
			set { this.m_vs["CurrentItemId"] = value; }
		}
	}

	public class ViewStateCurrentItemPropertyHolder : ViewStateCurrentItemPropertyHolder<ContentItem>
	{
		public ViewStateCurrentItemPropertyHolder(StateBag viewState): base(viewState)
		{
		}
	}
}
